﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Mono.Zeroconf;

namespace Jarvis.Sensors
{
    class BonjourSensor : Sensor
    {
        public List<object> services;
        ServiceBrowser browser;

        public BonjourSensor()
            : base(60000)
        {
            this.name = "Zeroconf Services Sensor";
            browser = null;
        }

        public override void Sense(Object stateInfo)
        {
            try
            {
                if (browser == null)
                {
                    browser = new ServiceBrowser();
                    browser.ServiceAdded += this.OnServiceAdded;
                }

                browser.Browse("_services._dns-sd._udp.", "");

                this.log(null);

                services = new List<object>();
            }
            catch (Exception)
            {

            }
        }

        private void OnServiceAdded(object o, ServiceBrowseEventArgs args)
        {
            try
            {
                IResolvableService service = args.Service;

                if (service.RegType.Equals("_tcp.local."))
                {
                    ServiceBrowser new_browser = new ServiceBrowser();
                    new_browser.ServiceAdded += this.OnServiceAdded;

                    new_browser.Browse(service.Name + "._tcp.", "local");
                }
                else
                {
                    service.Resolved += this.OnServiceResolved;
                    service.Resolve();
                }
            }
            catch (Exception)
            {

            }
        }

        private void OnServiceResolved(object o, ServiceResolvedEventArgs args)
        {
            try
            {
                IResolvableService service = o as IResolvableService;

                String service_desc = service.FullName.Replace("\\032", " ").Replace("\\.", ".");
                service_desc = service_desc.Replace("â€™", "'");

                service_desc = service_desc.Substring(0, service_desc.IndexOf("._"));
                service_desc = service_desc + " (" + service.RegType + ")";

                services.Add(service_desc);

                this.log(services);
            }
            catch (Exception)
            {

            }
        }
    }
}
